from etgui import *
from PageLayout import *
import os
#def IsWindows():return 1
def MakeDialog(title,model,inner):
	dialog=PotGuiDialog(
		model,
		inner,
		title,
		eWinBlock
	)
	return dialog
def SelectAFeature():
	if EnvGetBool("Sniff.AskForWelcomeLicense",0):
		model=PotGuiModel()
		popup=PotGuiOneOf("Feature")
		for item in ["SNiFF","SNiFF_CROSS","SNiFF_Win","SNiFF_Lite","SNiFF_EVAL"]:
			popup.AddItem(item,item)
		view=popup
		dialog=MakeOkCancelDialog("Select a feature",model,view)
		model.SetValue("Feature","SNiFF")
		if dialog.ShowUnderMouse()==CmdNo.cIdOk:
			return model.GetValue("Feature")
		else:
			return None
	else:
		fn=SLicenseGetFeatureNames("SNiFF")
		f=LMFeature("","",fn)
		return f.OkName()	

def StartOnlineDemo():
	model=PotGuiModel()
	view=VBox(
		items=[
			StyledTextItem("Start online demo",font=SFont(sizedelta=6)),
			MultilineTextItem(
				"The interactive online demo requires"
				"\nMicrosoft Internet Explorer 4.x (or newer) or"
				"\nNetscape 4.x (or newer). Make sure that the appropriate"
				"\nexecutable can be found in the path."
			)
		]
	)
	dialog=MakeOkCancelDialog("Start Online demo",model,view)
	dialog.ShowUnderMouse()

def PrintPDF(title,file):
	model=PotGuiModel()
	model.SetValue("File",file)
	view=VBox(
		items=[
			MultilineTextItem("@BPlease print the following PDF file using Adobe Acrobat:@B"),
			Filler(gPoint4),
			PotTextField("File",width=(2*len(file))/3),
			Filler(gPoint4),
			MultilineTextItem(
				"@BNote@B: If you don't have Adobe Acrobat installed, you can find it on the"
				"\nSNiFF+ CD (Acread30.zip) or you can download it from the FTP site"
				"\nwhere you downloaded SNiFF+."
			),
		]
	)
	dialog=MakeOkCancelDialog(
		title,
		model,
		view,
		ActionButton(CmdNo.cIdCancel,"Cancel",default=1)
	)
	dialog.ShowUnderMouse()

	
def PrintPostScript(title,file):
	model=PotGuiModel()
	printcmd=EnvGetString("General.Printer.Command","lp")
	fullcmd="zcat %s | %s" %(file,printcmd)
	model.SetValue("Print",fullcmd)
	view=VBox(
		items=[
			MultilineTextItem("@BThe selected tutorial will now be printed using the following command:@B"),
			Filler(gPoint4),
			PotTextField("Print",width=(2*len(fullcmd))/3),
			Filler(gPoint4),
			MultilineTextItem("Please edit the print command (lp) if necessary."),
		]
	)
	dialog=MakeOkCancelDialog(title,model,view)
	if dialog.ShowUnderMouse() == CmdNo.cIdOk:
		fullcmd=model.GetValue("Print")
		import vcs
		vcs.err=''
		rc=vcs.system(fullcmd)
		if rc:
			ShowAlert(eAlertNote,"@BPrint command@B\n@I%s@I\n@Bfailed:@B\n@I%s@I" %( fullcmd,vcs.err))


class ReadTutorial:
	if IsWindows():
		tutorials= (
			("C++",     "doc/online/cpp.chm",           "doc/C++tutorial.pdf"),
			("C",       "doc/online/c.chm",             "doc/CTutorial.pdf"),
			("Java",    "doc/online/java.chm",          "doc/JavaTutorial.pdf"),
			("Fortran", "doc/online/fortran.chm",       "doc/FortranTutorial.pdf"),
		)
	else:
		tutorials= (
			("C++",     "doc/online/cpp/cpp.htm",         "doc/C++tutorial.ps.Z"),
			("C",       "doc/online/c/c.htm",             "doc/CTutorial.ps.Z"),
			("Java",    "doc/online/java/java.htm",       "doc/JavaTutorial.ps.Z"),
			("Fortran", "doc/online/fortran/fortran.htm", "doc/FortranTutorial.ps.Z"),
		)
	helpmap={
		"C++":     "help:Tutorials_CPP",
		"C":       "help:Tutorials_C",
		"Java":    "help:Tutorials_Java",
		"Fortran": "help:Tutorials_Fortran",
	}
	def PrintTutorial(self):
		tutorial=self.model.GetValue("Tutorial")
		for name,online_file,print_file in self.GetAvailableTutorials():
			if tutorial==name:
				if not print_file:
					ShowAlert(eAlertNote,"No printable version of the %s tutorial available" %name)
				else:
					if IsWindows():
						PrintPDF("Print %s Tutorial" % tutorial,print_file)
					else:
						PrintPostScript("Print %s Tutorial" % tutorial,print_file)
	def BrowseTutorial(self):
		tutorial=self.model.GetValue("Tutorial")
		for name,online_file,print_file in self.GetAvailableTutorials():
			if tutorial==name:
				if not online_file:
					ShowAlert(eAlertNote,"No online_file version of the %s tutorial available" %name)
				else:
					HelpOnName(self.helpmap[name])
					#ShowURL("file:%s"%online_file)
		tutorial=self.model.GetValue("Tutorial")
	def GetAvailableTutorials(self):
		tutorials=[]
		for name,online_file,print_file in self.tutorials:
			online_file=self.ExpandFile(online_file)
			print_file=self.ExpandFile(print_file)
			if online_file or print_file:
				tutorials.append((name,online_file,print_file))
		return tutorials
	def ExpandFile(self,filename):
		import posixpath
		# we do a posixpath join because sniffdir contains /....
		path=posixpath.join(GetSniffDir(),filename)
		if os.path.exists(path):
			return path
		return ''
		
	def __call__(self):
		tutorials=self.GetAvailableTutorials()
		if not tutorials:
			ShowAlert(eAlertNote,"No Tutorials available!")
			return
		self.model=PotGuiModel()
		popup=PotGuiPopupButton("Tutorial")
		popup.RemoveAllItems()
		setvalue=1
		for key,online_file,print_file in tutorials:
			if setvalue:
				self.model.SetValue("Tutorial",key)
				setvalue=0
			popup.AddItem(key,key)
		if IsWindows():
			read_online_text=(
				"If you don't want to print the tutorial,"
				"\nyou can go through it online."
			)
		else:
			read_online_text=(
				"If you don't want to print the tutorial, you can"
				"\ngo through it online with Netscape 4.x. Make "
				"\nsure that the appropriate executable can be found"
				"\nin the path."
			)
			
		view=VBox(
			align=eVObjHExpand,
			items=[
				StyledTextItem("Tutorials",font=SFont(sizedelta=6)),
				Form(
					align=eVObjVBottom,
					items=(
						MultilineTextItem("Tutorial"),
						popup
					)
				),
				Filler(gPoint8),
				Separator(),
				Filler(gPoint8),
				HBox(
					align=eVObjVBottom|eVObjHGapExpand,
					items=[
						MultilineTextItem(
							"If you don't have a printed tutorial,"
							"\nyou can print one out before you start."
						),
						ActionButton(
							"More...",
							action=self.PrintTutorial
						)
					]
				),
				Filler(gPoint8),
				Separator(),
				Filler(gPoint8),
				HBox(
					align=eVObjVBottom|eVObjHGapExpand,
					items=[
						MultilineTextItem(read_online_text),
						ActionButton(
							CmdNo.cIdOk,
							"Start..."
						)
					]
				),
			]
		)
		dialog=MakeOkCancelDialog(
			"Choose a Tutorial",
			self.model,
			view,
			ActionButton(CmdNo.cIdCancel,"Cancel")
		)
		if dialog.ShowUnderMouse()==CmdNo.cIdOk:
			self.BrowseTutorial()

class MoreAboutLicense:
	def __init__(self,feature,text):
		self.feature=feature
		self.text=text
	def __call__(self):
		view= VBox(
			items=[
				StyledTextItem(self.feature,font=SFont(sizedelta=6)),
				MultilineTextItem(self.text)
			]
		)
		
		dialog=MakeOkCancelDialog(
			"More about %s" % self.feature,
			PotGuiModel(),
			view,
			ActionButton(CmdNo.cIdOk,"OK",default=1)
		)
		dialog.ShowUnderMouse()

def ShowSetupWizard():
	import SetupWizard
	SetupWizard.ShowModal()

lite_text=(
			"You are currently using @BPersonal SNiFF+@B."
			"\n"
			"\n@BPersonal SNiFF+@B is licensed for non-commercial use and evaluations"
			"\nonly. Commercial use is prohibited. While using Personal SNiFF+ project"
			"\nsize is limited to 200 files. In addition, remote development capabilities"
			"\nand code generation from the GUI builder are disabled."
			"\nPlease contact TakeFive Software at @bhttp://www.takefive.com@x"
			"\nif you would like to receive a free unlimited-use evaluation key or to"
			"\npurchase a permanent license key for commercial use."
			"\nFor details, please see the end-user license agreement."
)

def MakeView(feature):
	def MyMultilineTextItem(text):
		face=eFacePlain
		face=eFaceBold
		if face==eFaceBold:
			import regsub
			# bold in bold text becomes plain. Use italc instead
			#text=regsub.gsub('@B','@I',text)
			text=regsub.gsub('@B','',text)
		return MultilineTextItem(
			text,
			-1,
			SFont(face=face,sizedelta=0)
		)
	if feature == "SNiFF_Lite":
		section1=MyMultilineTextItem(
			lite_text
		)

	elif feature in ("SNiFF_EVAL","SNiFF_Lite_EVAL"):
		section1=MyMultilineTextItem(
			"You are running SNiFF+ with an @Bevaluation license@B."
		)
		lic="Evaluation License"
		lic_info=(
			"An evaluation license is valid for a limited period."
			"\nIt enables all SNiFF+ features on any machine"
			"\nand for an unlimited number of users."
		)

	else:
		section1=MyMultilineTextItem(
			"You are running SNiFF+ with a @Bvalid license@B."
		)
		lic="Product License"
		lic_info=(
			"A product license is valid for the number of users"
			"\nspecified and does not usually expire. For details"
			"\nabout your current license status choose "
			"\n@BLicenses...@B from the the Launch Pad's Help menu."
		)
	if feature == "SNiFF_Lite":
		more=Filler()
	else:
		more=ActionButton(
			"More...",action=MoreAboutLicense(lic,lic_info)
		)

	section1=HBox(
		align=eVObjVBottom|eVObjHGapExpand,
		items=[
			section1,
			more
		]
	)
	
	section2=VBox(
		align=eVObjHExpand,
		items=[
			HBox(
				align=eVObjVBottom|eVObjHGapExpand,
				items=[
					MyMultilineTextItem(
						"We recommend going through one of the language-specific"
						"\ntutorials to fully evaluate the product."
					),
					ActionButton(
						"Start...",
						action=ReadTutorial()
					)
				]
			)
		]
	)
	section3=HBox(
		align=eVObjVBottom|eVObjHGapExpand,
		items=[
			MyMultilineTextItem(
				"Check the SNiFF+ installation"
			),
			ActionButton(
				"Start...",
				action=ShowSetupWizard
			)
		]
	)
	def MySeparator():
		#return Filler(gPoint2,gInkBlack,flags=eVObjVFixed)
		return Separator()
	def MyFiller(point=Point(12)):
		return Filler(point,flags=eVObjVFixed)
	try:
		show_again= PotGuiToggleButton(
			"ShowWelcomeDialog",
			MyMultilineTextItem("Show this screen each time SNiFF+ starts")
		)
	except:
		show_again= PotGuiToggleButton(
			"ShowWelcomeDialog",
			"Show this screen each time SNiFF+ starts"
		)

	
	inner=VBox(
		align=eVObjVExpand|eVObjHExpand,
			items=[
				AlignBox(
				eVObjVCenter|eVObjHExpand,
				inner=VBox(
					align=eVObjHExpand,
					items=[
				section1,
						MyFiller(),
						MySeparator(),
						MyFiller(),
				section2,
						MyFiller(),
						MySeparator(),
						MyFiller(),
				section3,
						Filler(gPoint16)
					]
				)
			),
				HBox(
					align=eVObjVBase|eVObjHGapExpand,
					items=[
					show_again,
						ActionButton(CmdNo.cIdOk,"Close",default=1)
					]
				)
		],
	)
	# Change the following constatnts to adjust the margins
	left_gap=150
	top_gap=75
	height=391 # minimum heigth of the dialog
	width=588  # minimum width of the dialog
	box=VBox(
		align=eVObjVExpand|eVObjHExpand,
		#align=0,
		items=[
			Filler(gPoint0,flags=eVObjVFixed|eVObjHFixed),
			Filler(Point(width-left_gap,top_gap),flags=eVObjVFixed|eVObjHFixed),
			Filler(Point(left_gap,height-top_gap),flags=eVObjVFixed|eVObjHFixed),
			inner,
			]
		)
	box.SetColsRowsSize(gPoint2)
 
	m= Matte(
		gPointBorderGap,
		box
	)
	return AlignBox(
		eVObjVExpand|eVObjHExpand,
		inner=m,
		ink=MakeImageInk("welcome_background")
#		ink=RGBInk(253,255,232)
	)

def ShowSniffLiteDialog():
	dialog=MakeOkCancelDialog(
		"SNiFF+ Personal",
		PotGuiModel(),
		MultilineTextItem(lite_text),
		ActionButton(CmdNo.cIdOk,"OK",default=1)
	)
	dialog.ShowUnderMouse()

class WelcomeModel(DictPyModel):
	def DoSetValue(self,path,value):
		if path=="ShowWelcomeDialog":
			EnvSetBool("Sniff.ShowBeginnersModeWizard",value)
			EnvSave(1)
			#print "-->ShowWelcomeDialog",value
		return DictPyModel.DoSetValue(self,path,value)
	def DoGetValue(self,path):
		if path=="ShowWelcomeDialog":
			#print "ShowWelcomeDialog==",EnvGetBool("Sniff.ShowBeginnersModeWizard",1)
			return EnvGetBool("Sniff.ShowBeginnersModeWizard",1)
		# do not forget to call the superclass method
		return DictPyModel.DoGetValue(self,path)
 
 
gDialog=None
def Show(force=0):
	global gDialog
	feature=SelectAFeature()
	showAgain=EnvGetBool("Sniff.ShowBeginnersModeWizard",1)
	if not force and not showAgain:
		if feature == "SNiFF_Lite":
			ShowSniffLiteDialog()
		return
	if not gDialog:
		gDialog=PotGuiDialog(
			WelcomeModel(),
			MakeView(feature),
			"Welcome",
			eWinFixed
			#eWinBlock|eWinFixed
		)
	gDialog.ShowUnderMouse()
